<template>
  <el-dialog
    class="dialog"
    :title="title"
    v-model="dialogFormVisible"
    append-to-body
  >
    <generate-form
      v-if="formConf.fields.length"
      ref="generateFormRef"
      :form-conf="formConf"
      :page-form-model="formModel"
      :is-sub-form="true"
      :key="formParseKey"
    />
    <template #footer>
      <el-button @click="dialogFormVisible = false">{{ $t("common.cancel") }}</el-button>
      <el-button
        type="primary"
        @click="handleUpdate"
      >
        {{ $t("common.confirm") }}
      </el-button>
    </template>
  </el-dialog>
</template>

<script setup lang="ts" name="AddOrUpdate">
import { defineAsyncComponent, provide, ref, watch } from "vue";
import { i18n } from "@/i18n";

const GenerateForm = defineAsyncComponent(() => import("../../GenerateForm/GenerateForm.vue"));

provide("isSubForm", true);

const emit = defineEmits(["submit"]);

const props = defineProps({
  fields: {
    type: Array,
    default: () => []
  }
});

const formParseKey = ref(new Date().getTime());
const dialogFormVisible = ref(false);
const formModel = ref({});
const title = ref(i18n.global.t("common.add"));
const formConf = {
  fields: [] as any[],
  formKey: "",
  disabled: false,
  span: 24,
  size: "small",
  labelPosition: "top",
  labelWidth: 100,
  formRef: "elSubForm",
  formRules: "rules",
  gutter: 15,
  formBtns: false,
  resetBtn: false,
  theme: {
    backgroundImg: "",
    showFormTitle: true,
    showFormDescribe: true,
    showFormNumber: false,
    btnsColor: null
  }
};

// Watch for changes in props.fields
watch(
  () => props.fields,
  val => {
    formConf.fields = val;
  },
  { deep: true, immediate: true }
);

const generateFormRef = ref<any>(null);

// Method to handle form submission
const handleUpdate = () => {
  console.log(generateFormRef.value.genFormRef);
  generateFormRef.value.genFormRef.validate((valid: boolean) => {
    if (valid) {
      dialogFormVisible.value = false;
      emit("submit", generateFormRef.value.formModel);
    }
  });
};

// Method to show dialog
const showDialog = (data: any) => {
  if (data) {
    formModel.value = data;
    title.value = i18n.global.t("common.edit");
  } else {
    formModel.value = {};
    title.value = i18n.global.t("common.add");
  }
  dialogFormVisible.value = true;
  formParseKey.value += new Date().getTime();
};

defineExpose({
  showDialog
});
</script>

<style scoped>
@media screen and (max-width: 500px) {
  .dialog.body {
    width: 100%;
  }
}
</style>
